package com.netty.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author chengjy
 * @date 2025/4/29
 */
public class NioServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();// 监听器
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.bind(new InetSocketAddress("localhost", 8080));
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    ServerSocketChannel serviceChannel = (ServerSocketChannel) key.channel();
                    SocketChannel client = serviceChannel.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                }


                if (key.isReadable()) {
                    SocketChannel clientChannel = (SocketChannel) key.channel();

                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int length =  clientChannel.read(byteBuffer);

                    if(length == -1){
                        System.out.println("客户端断开连接" + clientChannel.getRemoteAddress());
                        clientChannel.close();
                    }else{
                        byteBuffer.flip();
                        byte[] data = new byte[byteBuffer.limit()];
                        byteBuffer.get(data);
                        String message = new String(data);
                        System.out.println(message);
                    }
                }
            }
        }
    }

}
